package xyz.dava.sync.fm.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import technology.tabula.CommandLineApp;
import xyz.dava.sync.fm.vo.BomRouteFileTO;
import xyz.dava.sync.fm.vo.DataItemItem;
import xyz.dava.sync.fm.vo.RoutingPdfOrigin;

import java.util.ArrayList;
import java.util.List;

@RestController
public class TestController {
    @RequestMapping("/test")
    public Object test() {
        try {
            String filePath = "D:\\test\\2.pdf";
            String[] args = new String[]{"-f=JSON", "-p=all", filePath};
            CommandLineParser parser = new DefaultParser();
            CommandLine cmd = parser.parse(CommandLineApp.buildOptions(), args);
            StringBuilder stringBuilder = new StringBuilder();
            new CommandLineApp(stringBuilder, cmd).extractTables(cmd);
            List<RoutingPdfOrigin> result = JSONUtil.toList(JSONUtil.parseArray(stringBuilder.toString()), RoutingPdfOrigin.class);
            List<BomRouteFileTO> files = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {//页
                RoutingPdfOrigin origin = result.get(i);
                List<List<DataItemItem>> data = origin.getData();
                for (int j = 4; j < data.size() - 4; j++) { //行
                    List<DataItemItem> line = data.get(j);
                    // 设备工装 名称4 编号5 数量6
                    if (StrUtil.isNotBlank(line.get(5).getText())) {
                        BomRouteFileTO f = new BomRouteFileTO();
                        f.setFileId("");
                        f.setName(line.get(4).getText());
                        f.setCode(line.get(5).getText());
                        f.setObjId("");
                        String countStr = line.get(6).getText();
                        f.setCount(NumberUtil.isNumber(countStr) ? Double.parseDouble(countStr) : 0D);
                        f.setType("1");
                        f.setFilePath("");
                        files.add(f);
                    }
                    // 工艺文件 名称7 编号8
                    if (StrUtil.isNotBlank(line.get(8).getText())) {
                        BomRouteFileTO f = new BomRouteFileTO();
                        f.setName(line.get(7).getText());
                        f.setCode(line.get(8).getText());
                        f.setCount(0D);
                        f.setType("2");
                        files.add(f);

                    }
                }
            }
            return files;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
